import { DataTypes, Model } from 'sequelize';
import sequelize from '../db';

class Role extends Model {
  public id!: string;
  public tenantId!: string | null;
  public name!: string;
  public description?: string;
  public isSystem!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
  public permissions?: any[];

  async hasPermission(resource: string, action: string): Promise<boolean> {
    if (!this.permissions) {
      // 需要加载权限
      const RolePermission = (await import('./RolePermission.model')).default;
      const Permission = (await import('./Permission.model')).default;
      
      const rolePermissions = await RolePermission.findAll({
        where: { roleId: this.id },
      });
      
      const permissionIds = rolePermissions.map((rp: any) => rp.permissionId);
      this.permissions = await Permission.findAll({
        where: { id: permissionIds },
      });
    }
    
    return this.permissions.some(
      (permission: any) => permission.resource === resource && permission.action === action,
    );
  }
}

Role.init(
  {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    tenantId: {
      type: DataTypes.UUID,
      allowNull: true,
      field: 'tenant_id',
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    isSystem: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      field: 'is_system',
    },
  },
  {
    sequelize,
    tableName: 'roles',
    underscored: true,
    timestamps: true,
  },
);

export default Role;

